package top.luqichuang.common.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import top.luqichuang.common.util.StringUtil;

/**
 * @author LuQiChuang
 * @desc
 * @date 2020/8/12 15:25
 * @ver 1.0
 */
public abstract class JsonStarter<T> {

    private JsonNode node = new JsonNode();

    protected boolean isDESC() {
        return true;
    }

    protected void dealData(JsonNode node) {

    }

    protected T dealDataList(JsonNode node) {
        return null;
    }

    public void startData(String json, String... conditions) {
        node.init(json);
        node.initConditions(conditions);
        dealData(node);
    }

    public List<T> startDataList(String json, String... conditions) {
        JSONArray jsonArray = null;
        if (conditions.length != 0) {
            node.init(json);
            int i = 0;
            for (String condition : conditions) {
                if (++i != conditions.length) {
                    node.init(node.jsonObject(condition));
                } else {
                    jsonArray = node.jsonArray(condition);
                }
            }
        } else {
            try {
                jsonArray = JSON.parseArray(json);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return startDataList(jsonArray);
    }

    public List<T> startDataList(JSONArray jsonArray) {
        List<T> list = new ArrayList<>();
        if (jsonArray != null) {
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                node.init(jsonObject);
                T t = dealDataList(node);
                if (t != null) {
                    list.add(t);
                }
            }
            if (!isDESC()) {
                StringUtil.swapList(list);
            }
        }
        return list;
    }
}
